﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace UTL
{
    /* Clase que permite establecer una conexion con una base de datos
     */
    public class UTL_Conexion
    {
        public static UTL_Conexion instancia = new UTL_Conexion();

        private SqlConnection connection = new SqlConnection(getConnectionString());
        private static string connectionString = "";
       
        public SqlConnection getConnection
        {
            get { return connection; }
        }
        
        public UTL_Conexion()
        {
            connection = new SqlConnection(getConnectionString());
        }

        private static string getConnectionString()
        {
            connectionString = "Data Source=NBK_PAU\\SQLEXPRESS;Initial Catalog=cmiv;Integrated Security=True";
            //connectionString = "Data Source=NBK_NACHO\\SQL2008R2;Initial Catalog=cmiv;Integrated Security=True";
            return connectionString;
        }
        
        private void openConnection()
        {
            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void closeConnection()
        {
            connection.Close();
        }

        public bool executeNonQuery(SqlCommand cmd)
        {
            try
            {
                this.openConnection();
                cmd.ExecuteNonQuery();
                this.closeConnection();
                return true;
            }
            catch (Exception)
            {
                this.closeConnection();
                return false;
                throw;
            }
        }

        public DataTable executeSelectQuery(SqlCommand cmd)
        {
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();

            try
            {
                this.openConnection();
                da.SelectCommand = cmd;
                da.Fill(dt);
                this.closeConnection();
                return dt;
            }
            catch (Exception)
            {
                this.closeConnection();
                return dt;
                throw;
            }
        }
    }
}
